package com.naiterui.ehp.ps.sms.factory;

import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.naiterui.ehp.bp.utils.lang.ConfigUtil;

/**
 * @author guoyongxiang
 * @date 2019-08-16 15:34
 * @since 1.0.0
 */
public class HuaweiApi {

    private static final Logger LOGGER = LoggerFactory.getLogger(HuaweiApi.class);

    private static final String BASE_URL = ConfigUtil.getString("api.huawei.base.url");
    private static final String APP_KEY = ConfigUtil.getString("api.huawei.appKey");
    private static final String APP_SECRET = ConfigUtil.getString("api.huawei.appSecret");
    private static final String STATUS_CALLBACK = ConfigUtil.getString("api.huawei.statusCallBack");

    //无需修改,用于格式化鉴权头域,给"X-WSSE"参数赋值
    private static final String WSSE_HEADER_FORMAT = "UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\"";
    //无需修改,用于格式化鉴权头域,给"Authorization"参数赋值
    private static final String AUTH_HEADER_VALUE = "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\"";

    /**
     * 发送单条短信
     *
     * @param phone
     * @param templateId
     * @param datas
     *
     * @return
     */
    public static String singleSend(String phone, String channelNumber, String templateId, String[] datas, Integer platformId) {
        //条件必填,国内短信关注,当templateId指定的模板类型为通用模板时生效且必填,必须是已审核通过的,与模板类型一致的签名名称
        //国际/港澳台短信不用关注该参数
        String signature = ""; //签名名称

        //必填,全局号码格式(包含国家码),示例:+8615123456789,多个号码之间用英文逗号分隔
        String receiver = "+86" + phone; //短信接收人号码

        //选填,短信状态报告接收地址,推荐使用域名,为空或者不填表示不接收状态报告
        String statusCallBack = STATUS_CALLBACK;

        /**
         * 选填,使用无变量模板时请赋空值 String templateParas = "";
         * 单变量模板示例:模板内容为"您的验证码是${NUM_6}"时,templateParas可填写为"[\"369751\"]"
         * 双变量模板示例:模板内容为"您有${NUM_2}件快递请到${TXT_32}领取"时,templateParas可填写为"[\"3\",\"人民公园正门\"]"
         * 查看更多模板格式规范:常见问题>业务规则>短信模板内容审核标准
         */
        String templateParas = datas != null && datas.length > 0 ? Arrays.stream(datas)
                                                                         .collect(Collectors.joining("\",\"", "[\"", "\"]")) : ""; //模板变量

        //请求Body,不携带签名名称时,signature请填null
        String body = buildRequestBody(channelNumber, receiver, templateId, templateParas, statusCallBack, signature, platformId + "");
        if (null == body || body.isEmpty()) {
            LOGGER.warn("发送华为短信 body is null. templateId:{}, phone:{}, data:{}", phone, templateId, templateParas);
            return null;
        }

        //请求Headers中的X-WSSE参数值
        String wsseHeader = buildWsseHeader(APP_KEY, APP_SECRET);
        if (null == wsseHeader || wsseHeader.isEmpty()) {
            LOGGER.warn("发送华为短信 wsse header is null. templateId:{}, phone:{}, data:{}", phone, templateId, templateParas);
            return null;
        }

        LOGGER.info("调用华为发送短信接口: url : {}, phone:{}, templateId:{}, data:{}", BASE_URL, phone, templateId, templateParas);

        //为防止因HTTPS证书认证失败造成API调用失败,需要先忽略证书信任问题
        CloseableHttpClient client = null;
        try {
            client = HttpClients.custom()
                                .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null,
                                        (x509CertChain, authType) -> true).build())
                                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                                .build();
        } catch (Exception e) {
            LOGGER.error("发送华为短信，构建请求头失败, phone:{}, templateId:{}, data:{}", phone, templateId, templateParas, e);
        }

        try {
            HttpResponse response = client.execute(RequestBuilder.create("POST")//请求方法POST
                                                                 .setUri(BASE_URL)
                                                                 .addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")
                                                                 .addHeader(HttpHeaders.AUTHORIZATION, AUTH_HEADER_VALUE)
                                                                 .addHeader("X-WSSE", wsseHeader)
                                                                 .setEntity(new StringEntity(body)).build());
            return EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            LOGGER.error("发送华为短信，HTTP请求异常, phone:{}, templateId:{}, data:{}", phone, templateId, templateParas, e);
        }

        return null;
    }

    /**
     * 构造请求Body体
     *
     * @param sender
     * @param receiver
     * @param templateId
     * @param templateParas
     * @param statusCallbackUrl
     * @param signature         | 签名名称,使用国内短信通用模板时填写
     *
     * @return
     */
    static String buildRequestBody(String sender, String receiver, String templateId, String templateParas,
                                   String statusCallbackUrl, String signature, String extend) {
        if (null == sender || null == receiver || null == templateId || sender.isEmpty() || receiver.isEmpty()
                || templateId.isEmpty()) {
            LOGGER.warn("buildRequestBody(): sender, receiver or templateId is null.");
            return null;
        }
        List<NameValuePair> keyValues = new ArrayList<NameValuePair>();

        keyValues.add(new BasicNameValuePair("from", sender));
        keyValues.add(new BasicNameValuePair("to", receiver));
        keyValues.add(new BasicNameValuePair("templateId", templateId));
        if (null != templateParas && !templateParas.isEmpty()) {
            keyValues.add(new BasicNameValuePair("templateParas", templateParas));
        }
        if (null != statusCallbackUrl && !statusCallbackUrl.isEmpty()) {
            keyValues.add(new BasicNameValuePair("statusCallback", statusCallbackUrl));
        }
        if (null != signature && !signature.isEmpty()) {
            keyValues.add(new BasicNameValuePair("signature", signature));
        }
        keyValues.add(new BasicNameValuePair("extend", extend));

        return URLEncodedUtils.format(keyValues, Charset.forName("UTF-8"));
    }

    /**
     * 构造X-WSSE参数值
     *
     * @param appKey
     * @param appSecret
     *
     * @return
     */
    static String buildWsseHeader(String appKey, String appSecret) {
        if (null == appKey || null == appSecret || appKey.isEmpty() || appSecret.isEmpty()) {
            LOGGER.warn("buildWsseHeader(): appKey or appSecret is null.");
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        String time = sdf.format(new Date()); //Created
        String nonce = UUID.randomUUID().toString().replace("-", ""); //Nonce

        byte[] passwordDigest = DigestUtils.sha256(nonce + time + appSecret);
        String hexDigest = Hex.encodeHexString(passwordDigest);

        //如果JDK版本是1.8,请加载原生Base64类,并使用如下代码
        String passwordDigestBase64Str = Base64.getEncoder().encodeToString(hexDigest.getBytes()); //PasswordDigest

        return String.format(WSSE_HEADER_FORMAT, appKey, passwordDigestBase64Str, nonce, time);
    }
}
